#pragma once
#include <muduo/base/Logging.h>
#include <muduo/base/AsyncLogging.h>
#include <string>
#include <unordered_map>
#include <memory>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <atomic>

static std::shared_ptr<muduo::AsyncLogging> g_logger = nullptr;

void outPutCallBack(const char *msg, int len)
{
    g_logger->append(msg, len);
}

bool Init_logger(const std::string &logLevel, const std::string &logDir, const std::string &logName, const uint64_t logRollSize, int flushInterval = 3)
{
        static std::unordered_map<std::string, muduo::Logger::LogLevel> LEVEL = {
            {"TRACE", muduo::Logger::TRACE},
            {"DEBUG", muduo::Logger::DEBUG},
            {"INFO", muduo::Logger::INFO},
            {"WARN", muduo::Logger::WARN},
            {"ERROR", muduo::Logger::ERROR},
            {"FATAL", muduo::Logger::FATAL}};

        std::unordered_map<std::string, muduo::Logger::LogLevel>::iterator it = LEVEL.find(logLevel);
        if (it == LEVEL.end())
        {
            return false;
        }

        // 异步日志
        std::string basename = logDir + logName;
        struct stat st;
        if (stat(logDir.c_str(), &st) == -1)
        {
            if (mkdir(logDir.c_str(), 0755) == -1) // 0755：所有者读写执行，其他读执行
            {
                std::cerr << "创建日志目录失败：" << strerror(errno) << std::endl;
                return false;
            }
        }
        g_logger = std::make_shared<muduo::AsyncLogging>(basename, logRollSize, flushInterval);
        if (!g_logger)
        {
            std::cerr << "创建异步日志对象失败" << std::endl;
            return false;
        }
        g_logger->start(); // 后台线程就绪

        // 设置全局日志等级
        muduo::Logger::setLogLevel(it->second);

        // 设置日志输出回调
        muduo::Logger::setOutput(outPutCallBack);
        return true;
}